// Copyright (C) 2009 Ken Smith
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include "lcd_t.hpp"
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <sstream>

lcd_t::lcd_t(std::string proc_path) :
    proc_path_(proc_path),
    valid_levels_(),
    current_level_(valid_levels_.begin())
{
}

void lcd_t::init(void)
{
    std::ifstream lcd_state_file(proc_path_.c_str());
    std::string dummy;
    int level = 0;

    lcd_state_file >> dummy;
    do
    {
        lcd_state_file >> level;
        valid_levels_.push_back(level);
    }
    while (level != 100);

    lcd_state_file >> dummy;
    lcd_state_file >> level;
  
    if (!valid_levels_.empty())
    {
        current_level_ = std::find(
            valid_levels_.begin(),
            valid_levels_.end(),
            level
        );
    }
    lcd_state_file.close();
}

void lcd_t::brighter(void)
{
    if (current_level_ != valid_levels_.end())
    {
        ++current_level_;
        commit();
    }
}

void lcd_t::dimmer(void)
{
    if (current_level_ != valid_levels_.begin())
    {
        --current_level_;
        commit();
    }
}

void lcd_t::commit(void)
{
    if (current_level_ != valid_levels_.end())
    {
        std::stringstream ss;
        ss << *current_level_;
        std::string new_level(ss.str());
        std::ofstream lcd_state_file(proc_path_.c_str());
        if (!lcd_state_file.is_open())
        {
            std::cerr
                << "lcd_t::brighter: couldn't open "
                << proc_path_
                << " for writing"
                << std::endl;
            return;
        }
        lcd_state_file << ss.str();
        lcd_state_file.close();
    }
}
